var http = require('http'),
 	Q = require('q'),
	url = require('url'),
	_ = require('lodash'),
	qs = require('querystring');

var entityCollection = require('../../../Base/server/controllers/EntityCollection'),
	whqohTransController = require('../../../ProduceWork/server/controllers/WhqohTrans.server.controller'),
	HttpPostErpController = require('./HttpPostErp.server.controller.js'),
	BaseEnum = require('../../../Base/server/controllers/Enum.js');

/*
 * 生单服务API: /api/barcodeinfo/CreateRcvRecord
 * [req]：req.body=
 {
	parameter:{
		OpType: "", //操作类型
		DocTypeEnum: "", //单据类型
		CultureName: "", //语言 zh-CN
		EntCode: "", //企业Code
		OrgCode: "", //组织Code
		UserCode: "", //用户Code U9
		RcvUser: "", //操作员ID： 智能制造平台
		RcvDateTime: "", //操作时间
		CreateDocJSON: "", //生单JSON,关键；
		DocDetialList: []  //明细结构
	}
}

其中：DocDetialList
DocDetial:{
	LotCode: "", //批号编码
	SeiBanCode: "", //番号编码
	WhCode: "", //存储地点编码
	BinCode: "", //库位编码
	Qty: "" //数量
}
 * [res]: 根据body中的ifsuccess判断使用 
 			res.bady={
 				ifsuccess : true/false,
    			data : "正确数据或者错误信息"
    		}
 */

exports.create= function(req, res){
	
	var parmater=req.body.Parameter;

	if (typeof(parmater)==='string'){
		parmater=JSON.parse(parmater);
	}

	if(!parmater.CreateDocJSON||!parmater.OperationKey){
		var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '生单失败';
        newErr.message = 'CreateDocJSON和OperationKey不能为空';
            
        res.json({ Error: newErr });
        res.end();

        return;
	}

	try{
		JSON.parse(parmater.CreateDocJSON);	
	}
	catch(err){
		var newErr = new Error();
        newErr.leval = 9;
        newErr.title = '生单失败';
        newErr.message = 'CreateDocJSON应为可转JSON格式的字符串，当前传递为' + parmater.CreateDocJSON;
            
        res.json({ Error: newErr });
        res.end();

        return;
	}

	if(parmater.IfWhTrans){
		createWhTransDoc(parmater, function(result){
			if (result.IfSuccess){
				if (result.IfHaveRtnMess){
					res.json({ Data: { Message: result.Message} });
				} else{
					res.json({ Data: { Message: "生出入库单据成功"} });
				}
			}else{
				var newErr = new Error();
			    newErr.leval = 9;
			    newErr.title = '生出入库单据失败';
			    newErr.message = result.ErrorMess;
				            
			    res.json({ Error: newErr });
			}

			res.end();
		})
	}else{
		createPendBusinessDoc(parmater, function(result){
			if (result.IfSuccess){
				if (result.IfHaveRtnMess){
					res.json({ Data: { Message: result.Message} });
				} else{
					res.json({ Data: { Message: "生待处理业务成功"} });
				}
			}else{
				var newErr = new Error();
			    newErr.leval = 9;
			    newErr.title = '生待处理业务失败';
			    newErr.message = result.ErrorMess;
				            
			    res.json({ Error: newErr });
			}

			res.end();
		})
	}
}

/*
 * 生单服务API: /api/barcodeinfo/CreateErpDoc
 * [req]: 前端调用使用
 */
exports.createErpDoc = function(req, res){
	var records = req.body;

	createDoc(records, function(result){
		if (result.IfSuccess){
			res.json({ Data: { Message: "生单成功"} });

		}else{
			var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '生单失败';
            newErr.message = result.ErrorMess;
            
            res.json({ Error: newErr });
		}

		res.end();
	});
}

/*
 * 内部方法：生成出入库记录以及调用U9生单服务
 *
 */
function createWhTransDoc(parmater, callbackFun){
var entityRcv=entityCollection.getEntity("WhTrans");
	var entityRcvDetial=entityCollection.getEntity("WhTransDetail");

	var records =[];
	var record={
		DocType : parmater.DocType,
		RcvUser : parmater.RcvUser,
		RcvDateTime : parmater.RcvDateTime,
		IsCreatedERPDoc : 0,
		IsSuccessCreatedErpDpc: 0,
		CreateDocJSON : parmater.CreateDocJSON,
		EntCode : parmater.EntCode,
		OrgCode : parmater.OrgCode,
		CreatedBy : parmater.RcvUser,
		RowStatus : BaseEnum.RowStatus.Insert.Value,
		OperationKey: parmater.OperationKey,
		UserCode: parmater.UserCode,
		CultureName: parmater.CultureName
	};

	//条码:Code
	if (parmater.Barcode) { record.Barcode=parmater.Barcode; }
	//AppKey
	if (parmater.AppKey) { record.AppKey=parmater.AppKey; }
	//单据编码：DocCode
	if (parmater.DocCode) { record.DocCode=parmater.DocCode; }
	// OperType //操作类别： 0，创建单据； 1，审核单据， 2：创建并审核单据
	if (parmater.OperType) { record.OperType=parmater.OperType; }
	// SourceDocNum 来源单据号
	if (parmater.SourceDocNum) { record.SourceDocNum=parmater.SourceDocNum; }
	// 业务组织名称
	if (parmater.BizOrgName) { record.BizOrgName=parmater.BizOrgName; }

	if(parmater.Direction){ record.Direction=parmater.Direction;}

	records.push(record);

	//主实体提交
	entityRcv.save(records, function(ierr, data) {
		if (ierr) {
			var rtnData ={};
			rtnData.IfSuccess=false;
            rtnData.ErrorMess=ierr.message;

            callbackFun(rtnData);

		} else {
			var dataID = data._id;
			//插入子实体
			var detialRecords=[];

		    _.forEach(parmater.DocDetialList, function (detial) {
		        var detialRecord={
		        	WhTrans: dataID,
		        	LotCode: detial.LotCode,
		        	SeiBanCode: detial.SeiBanCode,
		        	WhCode: detial.WhCode,
		        	BinCode: detial.BinCode,
		        	Qty: detial.Qty,
		        	RowStatus : BaseEnum.RowStatus.Insert.Value,
		        	ItemCode: detial.ItemCode
		        };

		      	//项目号
		    	if (detial.ProjectCode) { detialRecord.ProjectCode= detial.ProjectCode; }
		        //行号
		    	if (detial.DocLineNum) { detialRecord.DocLineNum= detial.DocLineNum; }
		    	//料品名称
		    	if (detial.ItemName) { detialRecord.ItemName= detial.ItemName; }
		        //等级
		        if (detial.DegreeCode) { detialRecord.DegreeCode= detial.DegreeCode; }
		        //成分
		    	if (detial.ElementCode) { detialRecord.ElementCode= detial.ElementCode; }
		    	//厂牌编码
		    	if (detial.SupplierCode) { detialRecord.SupplierCode= detial.SupplierCode; }
		    	//厂牌名称
		    	if (detial.SupplierName) { detialRecord.SupplierName= detial.SupplierName; }
		    	//存储类型: 0: 待检 1，可用  2，报废; 3 不合格
		    	if (detial.StoreType) { detialRecord.StoreType= detial.StoreType; }
		    	//条码
		    	if (detial.BarCode) { detialRecord.BarCode= detial.BarCode; }
		    	//货主组织名称
		    	if (detial.ItemOwnOrgName) { detialRecord.ItemOwnOrgName= detial.ItemOwnOrgName; }

		        detialRecords.push(detialRecord);
		    });

		    entityRcvDetial.save(detialRecords, function(ierr, dataDetial){
		    	if (ierr){
					var rtnData ={};
					rtnData.IfSuccess=false;
		            rtnData.ErrorMess=ierr.message;

		            callbackFun(rtnData);
		    	}else{
		    		//生成U9单据
		    		//PDA端：只要生成了智能制造平台的单据即可，即使未生成U9单据暂时也不报错到PDA端
		    		var datas=[];	
		    		datas.push(data._doc);

					createDoc(datas, 1, callbackFun);
		    	}
		    });
		}
	});
}


/*
 * 内部方法：生待处理单以及调用U9生单服务
 *
 */
function createPendBusinessDoc(parmater, callbackFun){
var entityRcv=entityCollection.getEntity("PendingBusiness");
	var entityRcvDetial=entityCollection.getEntity("PendingBusinessDetail");

	var records =[];
	var record={
		DocType : parmater.DocType,
		RcvUser : parmater.RcvUser,
		RcvDateTime : parmater.RcvDateTime,
		IsCreatedERPDoc : 0,
		IsSuccessCreatedErpDpc: 0,
		CreateDocJSON : parmater.CreateDocJSON,
		EntCode : parmater.EntCode,
		OrgCode : parmater.OrgCode,
		CreatedBy : parmater.RcvUser,
		RowStatus : BaseEnum.RowStatus.Insert.Value,
		OperationKey: parmater.OperationKey,
		UserCode: parmater.UserCode,
		CultureName: parmater.CultureName
	};

	//条码:Code
	if (parmater.Barcode) { record.Barcode=parmater.Barcode; }
	//AppKey
	if (parmater.AppKey) { record.AppKey=parmater.AppKey; }
	//单据编码：DocCode
	if (parmater.DocCode) { record.DocCode=parmater.DocCode; }
	// OperType //操作类别： 0，创建单据； 1，审核单据， 2：创建并审核单据
	if (parmater.OperType) { record.OperType=parmater.OperType; }
	// SourceDocNum 来源单据号
	if (parmater.SourceDocNum) { record.SourceDocNum=parmater.SourceDocNum; }
	// 业务组织名称
	if (parmater.BizOrgName) { record.BizOrgName=parmater.BizOrgName; }

	if(parmater.Direction){ record.Direction=parmater.Direction;}

	records.push(record);

	//主实体提交
	entityRcv.save(records, function(ierr, data) {
		if (ierr) {
			var rtnData ={};
			rtnData.IfSuccess=false;
            rtnData.ErrorMess=ierr.message;

            callbackFun(rtnData);

		} else {
			var dataID = data._id;
			//插入子实体
			var detialRecords=[];

		    _.forEach(parmater.DocDetialList, function (detial) {
		        var detialRecord={
		        	PendingBusiness: dataID,
		        	LotCode: detial.LotCode,
		        	SeiBanCode: detial.SeiBanCode,
		        	WhCode: detial.WhCode,
		        	BinCode: detial.BinCode,
		        	Qty: detial.Qty,
		        	RowStatus : BaseEnum.RowStatus.Insert.Value,
		        	ItemCode: detial.ItemCode
		        };

		      	//项目号
		    	if (detial.ProjectCode) { detialRecord.ProjectCode= detial.ProjectCode; }
		        //行号
		    	if (detial.DocLineNum) { detialRecord.DocLineNum= detial.DocLineNum; }
		    	//料品名称
		    	if (detial.ItemName) { detialRecord.ItemName= detial.ItemName; }
		        //等级
		        if (detial.DegreeCode) { detialRecord.DegreeCode= detial.DegreeCode; }
		        //成分
		    	if (detial.ElementCode) { detialRecord.ElementCode= detial.ElementCode; }
		    	//厂牌编码
		    	if (detial.SupplierCode) { detialRecord.SupplierCode= detial.SupplierCode; }
		    	//厂牌名称
		    	if (detial.SupplierName) { detialRecord.SupplierName= detial.SupplierName; }
		    	//存储类型: 0: 待检 1，可用  2，报废; 3 不合格
		    	if (detial.StoreType) { detialRecord.StoreType= detial.StoreType; }
		    	//条码
		    	if (detial.BarCode) { detialRecord.BarCode= detial.BarCode; }
		    	//货主组织名称
		    	if (detial.ItemOwnOrgName) { detialRecord.ItemOwnOrgName= detial.ItemOwnOrgName; }

		        detialRecords.push(detialRecord);
		    });

		    entityRcvDetial.save(detialRecords, function(ierr, dataDetial){
		    	if (ierr){
					var rtnData ={};
					rtnData.IfSuccess=false;
		            rtnData.ErrorMess=ierr.message;

		            callbackFun(rtnData);
		    	}else{
		    		//生成U9单据
		    		//PDA端：只要生成了智能制造平台的单据即可，即使未生成U9单据暂时也不报错到PDA端
		    		var datas=[];	
		    		datas.push(data._doc);

					createDoc(datas, 0, callbackFun);
		    	}
		    });
		}
	});
}

/*
 * 内部方法：生成U9单据
 *
 */
function createDoc(records, ifWhTrans, callbackFun){
	var option = {
		url : 'RestServices/UFIDA.U9.BC.Common.ICreateDocForPubSV.svc/Do'
	}

    _.forEach(records, function (record) {
    	var ParamIn = [];
        var param = {};
        var docList = [];

        var createDocJsonStr=JSON.parse(record.CreateDocJSON);

        if(_.isArray(createDocJsonStr)){
        	createDocJsonStr.forEach(function(createDocJson) {
      			docList.push(JSON.stringify(createDocJson));
    		});
        }else{
        	docList.push(record.CreateDocJSON);
        }

        param.DocTypeEnum=record.DocType;
        param.DocDetialJson=docList;
        param.DocID = record._id;
		param.OperatorKey = record.OperationKey;

        ParamIn.push(param);

		var context = {
			CultureName: record.CultureName,
			EntCode: record.EntCode,
			OrgCode: record.OrgCode,
			UserCode: record.UserCode
		};

		var CreatedDocKey="key";

		var params = {
			context: context,
			paramIn: ParamIn,
			createdDocKey: CreatedDocKey
		};

		HttpPostErpController.post(option, params, function(result){
			var entity = (ifWhTrans==1) 
				? entityCollection.getEntity("WhTrans")
				: entityCollection.getEntity("PendingBusiness");

			var recordID = result.DocID;

			if (result.IfSuccess){
				//更新智能制造平台数据
				entity.updateByValue({_id: recordID}, {IsSuccessCreatedErpDpc: 1, IsCreatedERPDoc: 1}, function(Error, result){
				})
			} else{
				//更新智能制造平台数据
				entity.updateByValue({_id: recordID}, {IsSuccessCreatedErpDpc: 0, IsCreatedERPDoc: 1, FailReason: result.ErrorMess}, 
					function(Error, result){
				})
			}

			callbackFun&&callbackFun(result);
		});
    });

}